package com.dmai.capacity.platform.oauth.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dmai.capacity.platform.common.context.TenantContextHolder;
import com.dmai.capacity.platform.common.model.LoginAppUser;
import com.dmai.capacity.platform.oauth.common.util.AuthUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Conditional;
import org.springframework.web.filter.OncePerRequestFilter;
import com.dmai.capacity.platform.common.context.SysUserContextHolder;

/**
 * 获取当前登录人过滤器
 */
@ConditionalOnClass(Filter.class)
@Conditional(FilterCondition.class)
public class LoginUserFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {

            LoginAppUser user = AuthUtils.getLoginAppUser();

            SysUserContextHolder.setUser(user);

            //保存租户id
            if (user != null && StringUtils.isNotEmpty(user.getTenantId())) {
                TenantContextHolder.setTenant(user.getTenantId());
            }

            filterChain.doFilter(request, response);
        } finally {
            SysUserContextHolder.clear();
            TenantContextHolder.clear();
        }
    }
}
